<template>
  <div class="rightBodyContent">
    <div class="rightBodyContent-in">
      <div class="search-list mb-10">
        <div style="display: flex; align-items: center; margin-right: 10px">
          <el-date-picker
            v-model="ruleForm.timeInterval"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            size="small"
            class="mr-10">
          </el-date-picker>
          <el-button type="primary" size="small" @click="searchFn('search')"><i class="el-icon-search"></i>搜索
          </el-button>
          <el-button size="small" @click="searchFn('refresh')"><i class="el-icon-refresh"></i>刷新</el-button>
        </div>
      </div>
      <template v-if="isIpSetting">
        <table width="100%" border="1" class="my-table" bordercolor="#dfe6ec">
          <tr>
            <th>日期</th>
            <th>巡更点</th>
            <th>巡更班次</th>
            <th>值班人/巡更时间</th>
            <th>当日漏更次数</th>
          </tr>
          <!--        // workList 训班次时间-->
          <!--        recodsList 日期-->
          <!--        pointList 巡更点-->
          <template v-if="recodsList.length">
            <template v-for="(day, dayindex) in recodsList">
              <template v-for="(point, pointindex) in pointList">
                <template v-if="day.keepTimeItems.length">
                  <tr :key="`${dayindex}-${pointindex}-${timeindex}`" v-for="(time, timeindex) in day.keepTimeItems">
                    <td :rowspan="pointList.length*day.keepTimeItems.length" v-if="!pointindex && !timeindex">
                      {{ day.timeInterval }}/{{ day.week }}
                    </td>
                    <td :rowspan="day.keepTimeItems.length" v-if="!timeindex">
                      {{ point.position }}
                    </td>
                    <td>
                      {{ time.keepTime }}
                    </td>
                    <td>
                      {{ time.point[point.id] ? time.point[point.id].clockTime : '' }}
                    </td>
                    <td :rowspan="day.keepTimeItems.length" v-if="!timeindex" style="color: #006dcd;font-weight:bold;">
                      {{ day.countData[point.id].number || '' }}
                    </td>
                  </tr>
                </template>
                <template v-else>
                  <tr :key="`${dayindex}-${pointindex}`">
                    <td>
                      {{ day.timeInterval }}/{{ day.week }}
                    </td>
                    <td>
                      {{ point.position }}
                    </td>
                    <td style="color: #999;">
                      当天未设置巡更时间
                    </td>
                    <td>

                    </td>
                    <td>
                    </td>
                  </tr>
                </template>
              </template>
            </template>
          </template>
          <template v-else>
            <tr>
              <td colspan="5">
                未找到相关记录
              </td>
            </tr>
          </template>
        </table>
      </template>
      <template v-else>
        <div style="padding: 40px;text-align: center;">
          本地巡更IP未设置
        </div>
      </template>
    </div>
  </div>
</template>

<script>
import {pagination} from "@/utils/util.js";
import {mapGetters} from "vuex";
import {devicelist, porstuser, qualityAdd, recdocList} from "@/api/xungen.js";

export default {
  components: {},
  computed: {
    ...mapGetters(["configData"]),
  },
  data() {
    return {
      timeData: "",
      pickerOptions1: {},
      dialogVisible: false,
      dialogVis: false, //巡更设备
      dialogTime: false, //巡更时间点
      tableStripe: true, // 是否斑马栏
      tableBorder: true, // 单元格右边边框
      pointList: [], // 数据列表
      cardUser: [],
      timeList: [], //时间点列表
      recodsList: [], //巡更记录
      // 页数
      page: {
        pageindex: pagination.pageIndex,
        pagesize: pagination.pageSize,
        total: pagination.total,
      },
      ruleForm: {
        cardNo: "",
        timeInterval: [], // '2024-04-13', '2024-04-18'
        deviceId: [],
        keepTimes: [],
      },
      isIpSetting: false
    };
  },
  created() {
    this.$set(this.ruleForm, 'timeInterval', [this.$toDay(new Date()), this.$toDay(new Date())])
    if (this.configData && this.configData.keep_url) {
      this.isIpSetting = true
      this.changeDev()
    }
  },
  methods: {
    search() {
      this.dialogVisible = true;
    },
    // 分页
    handleSizeChange(val) {
      this.page.pageindex = val;
      this.InitFn();
    },
    // change获取卡号
    handleUser() {
      let port_ = this.configData.keep_port
        ? ":" + this.configData.keep_port
        : "";
      porstuser(`${this.configData.keep_url}${port_}`, {}).then((res) => {
        console.log(res, "res");
        this.cardUser = res.rows;
      });
    },

    // 选择设备列表
    changeDev() {
      let port_ = this.configData.keep_port
        ? ":" + this.configData.keep_port
        : "";
      devicelist(`${this.configData.keep_url}${port_}`, {}).then((res) => {
        console.log(res.rows,'res.rowsdayin -----------')
        this.pointList = res.rows;
        this.submitForm()
      });
    },

    // 选择巡更时间列表
    changeKeeptime() {
      let port_ = this.configData.keep_port
        ? ":" + this.configData.keep_port
        : "";
      qualityAdd(`${this.configData.keep_url}${port_}`).then((res) => {
        this.timeList = res.rows;
      });
    },

    searchFn(item) {
      if (!this.isIpSetting) {
        this.$message.error('本地巡更IP未设置，请设置')
        return
      }
      if (item == 'refresh') {
        this.$set(this.ruleForm, 'timeInterval', [this.$toDay(new Date()), this.$toDay(new Date())])
      }
      this.submitForm()
    },
    submitForm() {
      let port_ = this.configData.keep_port
        ? ":" + this.configData.keep_port
        : "";
        let this_ = this
      recdocList(`${this.configData.keep_url}${port_}`, this.ruleForm).then(
        (res) => {
           // 当前时间时间戳
          let nowTime = new Date().getTime()
          let countData = {}

          for (let item of res.data) {
            let countDataObj = {list:[]}
            item.week = this.getWeekDay(item.timeInterval)
            for (let time of item.keepTimeItems) {
              let timeData = {}
              for (let point of time.device) {
                // let arr = []
                point.number = 0
                // console.log('point:',)
                // 如果当前时间戳小于巡更时间的时间戳(  漏更的意思是 当前时间大于巡更时间没打卡才算漏更 如果 当前时间小于巡更时间 没打卡也不算漏更 )
                if (nowTime > (new Date(item.timeInterval+' '+time.keepTime).getTime())) {
                  // 如果打卡了
                  // time.timeInterval
                  // time keepTime
                  //point  clockTime
                  if(!point.clockTime){
                    point.number+=1
                    // console.log(point.number ,'进入了123456219')
                  }else{
                    let a_ = point.clockTime.split('T')
                    let b_ = point.clockTime.split('T')[1].split('.')[0]
                    point.clockTime = `${a_[0]} ${b_}`
                    point.number = 0
                  }
                } else {
                  point.number = 0
                }

                timeData[point.deviceId] = point
                time.point = timeData
                // if(point.deviceId ==  time.point[point.deviceId].deviceId){
                countData[point.deviceId] = countDataObj
                // 将所有deviceid和漏更数push进list
                countData[point.deviceId].list.push({deviceId:point.deviceId,number:time.point[point.deviceId].number})
                // 深拷贝对象
                let countDataJson =  JSON.parse(JSON.stringify(countData))
                // 循环对象
                for(let count in  countDataJson){
                  let jsonArr = JSON.parse(JSON.stringify(countDataJson[count].list))
                  // 过滤每一项 将deviceid和key相同的过滤出来
                  countDataJson[count]['countArr'] = jsonArr.filter((element)=>{
                    return element.deviceId === Number(count)
                  })
                  // 删除没用的list属性
                  delete countDataJson[count].list
                  // 计算漏更数
                  let number = this_.totalNumber(countDataJson[count]['countArr'])
                  countDataJson[count]['number'] = number
                }
                item.countData = countDataJson
              }

            }
          }
          this.recodsList = res.data

          console.log('this.recodsList：',this.recodsList)

        }
      );
    },
    totalNumber(arr){
        let total = 0;
        arr.forEach(item => {
            total += item.number;
        });
        return total;
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.dialogVisible = false;
    },

    // 批量操作
    toggleSelection(data) {
      if (data == "device") {
        this.ruleForm.deviceId = this.$refs.deviceTable.selection.map(
          (v) => v.id
        );
        this.dialogVis = false;
      } else if (data == "keeptime") {
        this.ruleForm.keepTimes = this.$refs.keeptimeTable.selection.map(
          (v) => v.times
        );
        this.dialogTime = false;
      }
    },

    toggleClear(data) {
      if (data == "device") {
        this.$refs.deviceTable.clearSelection();
        this.dialogVis = false;
      } else if (data == "keeptime") {
        this.$refs.keeptimeTable.clearSelection();
        this.dialogTime = false;
      }
    },
    getWeekDay(dateString) {
      let weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
      let date = new Date(dateString);
      let dayOfWeek = date.getDay();
      return weekdays[dayOfWeek];
    }
  },
};
</script>
<style>
.lead-list {
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fddeae;
  margin-bottom: 5px;
  border-radius: 2px;
  padding: 5px 0;
}

.lead-list:last-child {
  margin-bottom: 0;
}

.lead-list span {
  margin-right: 30px;
}

table {
  border-collapse: collapse;
}

table th {
  height: 40px;
  background: #dfefff;
}

table td {
  text-align: center;
  padding: 7px 0;
}
</style>

